const {
  async
} = require("../../utils/runtime")

// pages/post/post-detail/post-detail.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    modalHidden: true,
    item: [],
    isLike: false,
    id: 0, //商品编号
    product_name: '理肤泉安心特安柔肤水',
    pic: 'https://gd3.alicdn.com/imgextra/i3/3929363300/O1CN01w8ttaG1aFRVY8N5dX_!!3929363300.jpg',
    bind_sum: 0,
    ID: '',
    modal_cost: '',
    modal_id: 0,
    modal_sum: 1,
    cost: 0,
    product_kan_sum:[],
    isfan:false,
    phone:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      phone : app.globalData.phone
    })
    console.log(app.globalData.res)
    var product_items = app.globalData.product //产品所有数组
    var sum = app.globalData.product_sum //产品个数
    var product_item = [] //显示的产品
    var that = this
    var id = options.id
    console.log(id) //产品的 product_code
    console.log(product_items[0])
    for (var i = 0; i < sum; i++) {
      if (product_items[i].product_code == id) { //找到该商品
        var product_item = product_items[i]
        console.log(product_item.modal_cost_advise)
        var item = product_item.modal_cost_advise
        console.log(product_item)
        console.log(item)
        that.setData({
          product_item: product_item,
          product_code_id: options.id,
          modal_total: item[1],
          // ID:product_item._id
        })
      }
    }

    var postId = options.id;
    var postDetail = this.data.item[postId - 1];
    this.setData({
      postDetail: postDetail
    })
  },
  sousuo:function(e){
    wx.navigateTo({
      url: '/pages/pingtuan/pingtuan-detail/pingtuan-detail?id='+this.data.product_item.product_code,
    })
  },
  kk:function(e){
    this.setData({
      isfan:false
    })
  },
  onShareTap: function (e) {
    var that = this
    var itemList = [
      "分享给微信好友",
      "分享到朋友圈",
    ]

    wx.showActionSheet({
      itemList: itemList,
      itemColor: "#405f80",
      success: function (res) {
        wx.showModal({
          title: '用户' + itemList[res.tapIndex],
          content: ' 是否分享？',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.onShareAppMessage()
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

      }
    })
  },
  like: function (e) {
    var that = this
    if (that.data.bind_sum <= 4) {
      if (this.data.isLike == false) {
        wx.showToast({
          title: '收藏成功',
          icon: 'success'
        })
        let tableName = 'love'
        let recordID = that.data.ID // 数据行 id
        let Product = new wx.BaaS.TableObject(tableName)
        let product = Product.getWithoutData(recordID)

        product.append('product_code', that.data.product_item.product_code) //在知晓云中列入邀请人
        product.update().then(res => {

        }, err => {
          // err
        })
      } else {
        wx.showToast({
          title: '取消成功',
          icon: 'success'
        })
        let tableName = 'love'
        let recordID = that.data.ID // 数据行 id
        let Product = new wx.BaaS.TableObject(tableName)
        let product = Product.getWithoutData(recordID)

        product.remove('product_code', that.data.product_item.product_code) //在知晓云中列入邀请人
        product.update().then(res => {

        }, err => {
          // err
        })
      }
      // console.log(wx.getStorageSync('isLike'))
      setTimeout(function (e) {
        that.setData({
          isLike: !that.data.isLike,
          bind_sum: that.data.bind_sum + 1
        })
      }, 200)

    } else {
      wx.showToast({
        title: '点击太快，请休息一会哦',
        icon: 'none'
      })
    }
  },
  cantuan:function(e){
    this.setData({
      isfan:true
    })
  },
  onShareAppMessage: function (options) {

    var that = this

    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      console.log(res.target); // shareBtn
      // 此处可以修改 shareObj 中的内容

    };
    // 返回shareObj
    return {
      title: that.data.name,
      path: '/pages/post-detail/post-detail',
      imageUrl: this.data.product_item.product_swiper_pic1
    };
  },
  SetShoppingcar: function (e) {

    var phone = app.globalData.phone //获取用户电话
    let tableName = 'shoppingcar'
    let Query = new wx.BaaS.Query()
    Query.compare('phone', '=', phone)
    Query.compare('product_code', '=', this.data.product_code_id)
    Query.compare('name', '=', this.data.modal_total)
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      console.log(res)
      this.setData({
        shoppingcar: res.data.objects
      })
      console.log(this.data.shoppingcar)
    }), err => {
      // err
    }
    if (this.data.shoppingcar == null) {
      let Product = new wx.BaaS.TableObject(tableName)
      let product = Product.create()
      console.log(this.data.modal_total)
      let apple = {
        phone: phone,
        product_code: this.data.product_item.product_code,
        num: 1,
        name:this.data.modal_total.toString()
      }

      product.set(apple).save().then(res => {
        console.log(res)
         wx.showToast({
        title: '添加成功',
        icon: 'none'
      })
      }, err => {
        // err
      })
    } else {
      wx.showToast({
        title: '您的购物车已经有了这件宝贝咯',
        icon: 'none'
      })
    }
    this.setData({
      modalHidden:true
    })
  },
  onShow: function (e) {
    var time = new Date();
    var year = time.getFullYear()
    var mouth = time.getMonth()+1
    var day = time.getDate()
    var date = year + '-' + mouth + '-' + day 
    console.log(date)
    if(wx.getStorageSync('product_kan_sum') != ''){
      var product = wx.getStorageSync('product_kan_sum')
      var index = 0
      for(var i = 0 ; i < product.length ; i++){
        if(product[i].product_code == this.data.product_item.product_code){
          index = 1
          product[i].product_kan_sum = product[i].product_kan_sum + 1
          product[i].time.push(date)
          wx.setStorageSync('k', 1)
          wx.setStorageSync('product_kan_sum', product)
        }
       
      }
      if(index == 0){
        var item = {
          product_code:this.data.product_item.product_code,
          product_kan_sum:1,
          time:[date],
          id:this.data.product_item._id,
      
        }
        product.push(item)
        wx.setStorageSync('k', 1)
        wx.setStorageSync('product_kan_sum',product)
      }
    }else{
      var item = {
        product_code:this.data.product_item.product_code,
        product_kan_sum:1,
        time:[date],
        id:this.data.product_item._id,
      }
      wx.setStorageSync('product_kan_sum',[])
      wx.setStorageSync('k', 1)
      var product = wx.getStorageSync('product_kan_sum')
      product.push(item)
      wx.setStorageSync('product_kan_sum', product)
      // wx.setStorageSync('product_kan_sum', )
    }
    this.setData({
      address:app.globalData.address
    })
    console.log(this.data.address)
    var that = this
    let tableName = 'love'

    let Query = new wx.BaaS.Query()
    // Query.compare('product_code', '=', that.data.product_item.product_code)
    Query.compare('phone', '=', app.globalData.phone)
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      this.setData({
        ID: res.data.objects[0]._id
      })
      console.log(res.data.objects[0])
      for (var i = 0; i < res.data.objects[0].product_code.length; i++) {
        if (res.data.objects[0].product_code[i] == that.data.product_item.product_code) {
          that.setData({
            isLike: true,
            ID: res.data.objects[0].id
          })
          console.log(this.data.ID)
          console.log(111)
        }
      }
      console.log(res.data.objects[0].id)
      console.log(that.data.isLike)
    }, err => {
      // err
    })
    
  },

  onPay: function (e) {
    console.log(e.currentTarget.dataset.id)
    this.setData({
      index:e.currentTarget.dataset.id
    })
    console.log(this.data.product_item.modal_cost_advise)
    var items = []
    for (var i = 0; i < this.data.product_item.modal_cost_advise.length; i++) {
      var modal_cost_advise = this.data.product_item.modal_cost_advise[i].split(',')
      var item = {
        modal_cost: app.cost(wx.getStorageSync('dengji'),modal_cost_advise[0]),
        modal_total: modal_cost_advise[1]
      }
      items.push(item)
    }
    console.log(items)
    this.setData({
      modal: items,
      modal_cost: items[0].modal_cost,
      cost: items[0].modal_cost
    })

    this.setData({
      modalHidden: false
    })

  },
  modalConfirm: async function (e) {
    // if()
    this.setData({
      modalHidden: true
    })
    var merchandiseSnapshot = {
      电话: app.globalData.phone,
      金额: this.data.modal_cost ,
      页面: '商品页'
    }
    wx.setStorageSync('res', '')
    console.log(this.data.product_code_id)
    await app.pay_product(parseInt(this.data.modal_cost ), this.data.modal[this.data.modal_id].modal_total, merchandiseSnapshot, this.data.product_code_id)

  
    var res = wx.getStorageSync('res')
    // app.globalData.isPay = true
    console.log(res)
    app.globalData.dingdanhao = res.transaction_no

    this.setOrder(res)
  },

  setOrder(res){
    console.log('set:111')
    var that = this
    if (wx.getStorageSync('res') != '') {
      console.log('set:222')
      let tableName = 'Order'
      let Product = new wx.BaaS.TableObject(tableName)
      let product = Product.create()
      var myDate = new Date();
      var mytime = myDate.toLocaleString();
      console.log(mytime)
      // 设置方式一
      // let apple = {
      //   name: that.data.product_name, //商品名称
      //   sum: that.data.modal_sum, //购买数量
      //   product_code: that.data.product_code_id, //产品编号
      //   phone: app.globalData.phone, //用户手机号
      //   transaction_no: app.globalData.dingdanhao, //流水号
      //   return_money: 1, //返利钱
      //   actual_price: that.data.modal_cost , //实际价格
      //   all_price: that.data.product_item.pre_cost, //原价
      //   payment_time: mytime //时间
      // }
      console.log(that.data.modal_total.toString())
      console.log(parseInt(that.data.modal_sum))
      console.log(that.data.product_code_id.toString())
      console.log(that.data.phone)
      console.log(res.transaction_no.toString())
      console.log((that.data.modal_cost ).toString())
      console.log((that.data.product_item.pre_cost).toString())
      console.log(mytime.toString())
      console.log(that.data.address.toString())
      let apple = {
        name: that.data.modal_total.toString(),
        sum: parseInt(that.data.modal_sum), //购买数量
        product_code: that.data.product_code_id.toString(), //产品编号
        phone: that.data.phone.toString(), //用户手机号
        transaction_no: res.transaction_no.toString(), //流水号
        return_money: 1, //返利钱
        actual_price: (that.data.modal_cost ).toString(), //实际价格
        all_price: (that.data.product_item.pre_cost).toString(), //原价
        payment_time: mytime.toString(), //时间
        address: that.data.address.toString(),
        fukuan: 1
      }
      console.log(apple)
      product.set(apple).save().then(res => {
        // success
        console.log(res)
        setTimeout(function(e){
          wx.redirectTo({
            url: '../post-detail/post-detail-buy/post-detail-buy?id=' + app.globalData.dingdanhao.toString(),
          })
        },500)
      }, err => {
        //err 为 HError 对象
      })

    }
  },
  modalCandel: function (e) {
    this.setData({
      modalHidden: true
    })
  },
  GoDetail: function (e) {
    var postid = e.currentTarget.dataset.postid
    console.log(this.data.modal[postid])
    this.setData({
      modal_cost: this.data.modal[postid].modal_cost ,
      modal_id: postid
    })
    console.log(this.data.modal_cost);
  },
  addCount(e) {

    let num = this.data.modal_sum;
    if (num >= 5) {
      wx.showToast({
        title: '已经是最多数量啦',
        icon: 'none'
      })
    } else {
      num = num + 1;
    }
    this.setData({
      modal_cost: (num * parseInt(this.data.cost )).toString() ,
      modal_sum: num
    });

  },
  // 减少数量
  minusCount(e) {
    let num = this.data.modal_sum;
    if (num <= 1) {
      wx.showToast({
        title: '已经是最少数量啦',
        icon: 'none'
      })
    } else {
      num = num - 1;
    }
    this.setData({
      modal_cost: (num * parseInt(this.data.cost )).toString() ,
      modal_sum: num
    });

  },
  onAddress:function(e){
    wx.navigateTo({
      url: '/pages/addresDetail/addresDetail',
    })
  }
})